package com.it.service.biz;

import com.alibaba.fastjson.JSON;
import com.it.model.Chapter;
import com.it.utils.Logs;
import com.it.utils.Pair;
import com.it.utils.SnowFlake;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/6/12 2:19 下午
 */
@Component
public class ChapterBiz {


    @Value("${file.upload.directory}")
    private String uploadDir;

    public List<Chapter> decompressAndExtractBooks(Path compressedFile, Long bookId) throws IOException {
        List<Chapter> chaptes = new ArrayList<>();
        String destinationDirectory = uploadDir + "/chapters";
        String fileSeparator = System.getProperty("file.separator");
        try (ZipFile zipFile = new ZipFile(compressedFile.toFile())) {
            Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                if (entry.getName().startsWith("__MACOSX/")) {
                    continue;
                }
                if (!entry.isDirectory()) {
                    String entryName = entry.getName();
                    Path destinationPath = Paths.get(destinationDirectory, entryName);
                    Files.createDirectories(destinationPath.getParent());
                    Files.copy(zipFile.getInputStream(entry), destinationPath, StandardCopyOption.REPLACE_EXISTING);
                    Chapter chapter = new Chapter();
                    chapter.setBookId(bookId);
                    chapter.setId(SnowFlake.getInstance().genUuid());
                    chapter.setChapterName(entryName.substring(entryName.lastIndexOf(fileSeparator) + 1));
                    chapter.setChapterPath("/static/" + destinationPath.toString().replace(uploadDir, ""));
                    chapter.setCreateTime(System.currentTimeMillis()/ 1000L);
                    chapter.setLastUpdateTime(System.currentTimeMillis()/ 1000L);
                    Logs.common.info(Pair.of("chapter", JSON.toJSONString(chapter)));
                    chaptes.add(chapter);
                }
            }
        }
        return chaptes;
    }

}
